class Ticket < ActiveRecord::Base
	has_many :notes, :dependent => :destroy, :finder_sql => 'SELECT n.*, t.priority FROM note_types t, notes n ' + 
	' WHERE (t.id = n.note_type_id) AND n.ticket_id = #{id}' +
	' ORDER BY t.priority'
	belongs_to :group
	belongs_to :ticket_template
  validates_presence_of :name
  validates_length_of :name, :within => 1..100
  validates_presence_of :ticket_template
  validates_presence_of :number
  validates_uniqueness_of :number
  before_create :create_number
  after_update :save_notes 
  validates_associated :notes
  has_many :comments, :dependent => :destroy, :order => "created_at"
  belongs_to :updated_by,
             :class_name => "User",
             :foreign_key => "updated_by"
  belongs_to :created_by,
             :class_name => "User",
             :foreign_key => "created_by"
  attr_protected  :status
      

  def notes_attr=(nt_attributes)
    nt_attributes.each do |attributes|
      if attributes[:id].blank?
        note = Note.new(:note_type_id => attributes[:note_type_id])
        note.value = attributes[:value]
        notes << note 
      else
        note = notes.detect { |t| t.id == attributes[:id].to_i }
        note.value = attributes[:value]
      end
    end
  end
  
  def save_notes
    notes.each do |t|
      t.save(false)
    end
  end
	
  def finished?
    result = true
    self.notes.each do |note|
      if result and (note.note_type.vtype == 'vcheckbox') and (note.bvalue == false)
	      result = false
      end
    end
    result
  end
  
  def notes_col(i) # returns notes from selected column
    notes.select {|t| t.note_type.col_number == i }
  end
  
  def create_number
    t = Date.today
    r =  Ticket.find(:first, :order => "number DESC")
    num = ((t.year%1000).to_s+("%02d" % t.month.to_s)+("%02d" % t.mday.to_s)+"01").to_i
    if r.nil? or (r.number < num)
      self.number = num
    else
      self.number = r.number + 1
    end
  end
  
  def after_save
    if self.status != self.finished?
      self.status = !self.status
      self.save!
    end
  end
  
  def validate
    if self.notes.size != self.ticket_template.note_types.size
      errors.add(:notes, "Bad number of notes")
    end
  end

end
